<?php

namespace common\models;

use yii\web\IdentityInterface;
use Yii;

/**
 * Class BaseUser
 * @package common\models
 *
 * @property string $auth_key
 * @property string $password_hash
 */
class BaseUser extends BaseLockableActiveRecord implements IdentityInterface
{
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public static function findIdentity($id)
    {
        return static::find()->andWhere([
            'id' => $id,
        ])->limit(1)
            ->one();
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::find()->andWhere([
            'auth_key' => $token,
        ])->limit(1)
            ->one();
    }


    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }


    public static function findByWechatOpenId(string $openId)
    {
//        return static::find()->andWhere([
//            'wechat_open_id' => $openId,
//        ])->limit(1)
//            ->one();
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        if ($this->isNewRecord) {
            $this->generateAuthKey();
        }

        return true;
    }

    public static function findById(int $id)
    {
        return static::find()->andWhere([
            'id' => $id,
        ])->limit(1)
            ->one();
    }
}
